package com.bestv.search.common.util;

import org.apache.poi.hssf.usermodel.*;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class Excel {

    private HSSFWorkbook wb;
    private HSSFCellStyle centerStyle;
    private HSSFCellStyle leftStyle;

    public Excel() {
        // Creates one webBook that same with create one excel file.
        wb = new HSSFWorkbook();
        centerStyle = wb.createCellStyle();
        centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        leftStyle = wb.createCellStyle();
        leftStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    }

    public HSSFWorkbook create(List<ExcelSheet> sheets) {
        for (ExcelSheet sheet : sheets) {
            int maxCol = 0;

            // Create sheet
            HSSFSheet hssfSheet = wb.createSheet(sheet.getSheetName());

            // Create table header/ first row
            HSSFRow header = hssfSheet.createRow(0);

            // Sets first row align center
            header.setRowStyle(centerStyle);
            if (sheet.getDataHeader() != null || sheet.getDataHeader().size() > 0) {
                for (int i = 0; i < sheet.getDataHeader().size(); i++) {
                    HSSFCell headerCell = header.createCell(i);
                    headerCell.setCellValue(sheet.getDataHeader().get(i));
                }

                maxCol = sheet.getDataHeader().size();

                if (sheet.getData() != null) {
                    for (int i = 0; i < sheet.getData().size(); i++) {
                        HSSFRow row = hssfSheet.createRow(i + 1);
                        row.setRowStyle(leftStyle);
                        String[] values = sheet.getData().get(i);
                        for (int j = 0; j < values.length; j++) {
                            HSSFCell cell = row.createCell(j);
                            cell.setCellValue(values[j]);
                        }

                        if (maxCol < values.length) {
                            maxCol = values.length;
                        }
                    }
                }
            } else {
                wb = null;
            }

            for (int i = 0; i < maxCol; i++) {
                hssfSheet.autoSizeColumn((short) i);
            }
        }

        return wb;
    }

    public HSSFWorkbook create(ExcelSheet sheet) {
        List<ExcelSheet> list = new ArrayList<ExcelSheet>();
        list.add(sheet);

        return create(list);
    }

    public HSSFWorkbook insertPicture(HSSFSheet sheet, ByteArrayOutputStream picture, int startCol, int startRow) {
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255, (short) startCol, startRow, (short) 5, 5);
        anchor.setAnchorType(3);

        // 插入图片
        patriarch.createPicture(anchor, wb.addPicture(picture.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1);
        return wb;
    }
}
